# -*- coding: utf-8 -*-
from legendaryPowerScript import fighters
from legendaryPowerScript._lpcommon import apiUtil
from legendaryPowerScript._lpcommon.pluginManager import CommandExecuter
from legendaryPowerScript.item.legendaryItem import LegendaryItem
from templateServerScript import templateServerSystem


class ViewItemCommand(CommandExecuter):

    def __init__(self):
        CommandExecuter.__init__(self)
        self._actions = {
            "open": self.viewCommand,
        }
        self.lastViewedItems = {}
        templateServerSystem.mainSys.RegisterEventClient("ClientClaimViewItems", self, self.onClientClaimViewItems)

    def onClientClaimViewItems(self, data):
        print "onClientClaimViewItems", data
        fighter = apiUtil.getFighterById(data["playerId"])
        if not fighter:
            return
        if fighter.entityId not in self.lastViewedItems:
            fighter.sendHoverMessage("你没有打开过领取界面！")
            return
        item = self.lastViewedItems[fighter.entityId][data["index"]]
        hasGot = fighter.getVariable("got_viewitem_%s" % (item.typeName))
        if hasGot:
            fighter.sendHoverMessage("你已经领取过%s了！" % (item.typeName))
            return
        fighter.setVariable("got_viewitem_%s" % (item.typeName), 1)
        fighter.giveItem(item)
        fighter.sendHoverMessage("成功领取%s！" % (item.typeName))

    def viewCommand(self, sender, args):
        # 获取指定的玩家
        playerName = args[0]
        fighter = apiUtil.getFighterByName(playerName)
        print playerName, fighter

        uiPacket = []
        # 将后面的参数转化为物品表达式
        split = " ".join(args[1:]).split(";")  # list[物品表达式]
        itemsCache = []
        for itemParam in split:
            item = LegendaryItem.fromParam(itemParam, fighter)  # type: LegendaryItem
            itemsCache.append(item)
            # 玩家是否已领取过此物品，直接用变量存比较省事
            hasGot = fighter.getVariable("got_viewitem_%s" % (item.typeName))
            uiPacket.append({
                "item": item.itemDict,
                "got": hasGot
            })
        self.lastViewedItems[fighter.entityId] = itemsCache
        # 将物品信息发送给客户端，通知其打开界面
        templateServerSystem.mainSys.NotifyToClient(fighter.entityId, "ViewItemsEvent", uiPacket)

    def help(self, sender):
        sender.sendMessage(".viewitem open 玩家名 物品表达式1;物品表达式2…: 为玩家打开查看物品界面555")
